package com.cheng.spider.util;

import org.apache.http.Header;
import org.apache.http.HttpResponse;

import java.io.*;

public class ResponsePrinter {

    private HttpResponse response;

    public ResponsePrinter(HttpResponse response) {
        this.response = response;
    }

    public void printStausLine() {
        System.out.println(response.getStatusLine());
    }

    public void printHeaders() {
        for(Header header : response.getAllHeaders()) {
            System.out.println(header.getName()  + ": " + header.getValue());
        }
    }

    public void printResponseBody() {
        try {
            InputStream in = null;
            in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String s;
            while ((s = reader.readLine()) != null) {
                System.out.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveBodyAsImg(OutputStream outputStream) throws IOException {
        response.getEntity().writeTo(outputStream);
    }

    public void printResponse() {
        printStausLine();
        printHeaders();
        System.out.println();
        printResponseBody();
    }

    public void printResponseNoBody() {
        printStausLine();
        printHeaders();
        System.out.println();
    }
}
